package cn.sollyu.SDManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import cn.sollyu.SDManger.R;

	public class MainActivity extends Activity
	{
		
	/** Called when the activity is first created. */
	
	// 主界面中显示文件列表的全局标识
	ListView	listView	= null;
	// 文件列表存放变量
	ArrayList<HashMap<String, Object>> arrayList; 
	// 当前在列表选中的具体对应的数据结构
	private HashMap<String, Object> nowSelectHashMap;
	private String nowPathString;
	
	private static final int MESSGER_CLEAR_LIST_STRING = 0;
	private static final int MESSGER_DISPLAY_LIST_STRING = 1;
	private static final int MESSGER_SET_TITLE_STRING = 2;
	 private Handler mhandler; 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		ReleaseDatabase();
		
		listView = (ListView) this.findViewById(R.id.fileListView);
		
		displayFileList(Environment.getExternalStorageDirectory().getAbsolutePath());
		
		listView.setOnItemClickListener(new OnListViewItemClickListener());
		listView.setOnCreateContextMenuListener(new OnListViewCreateContextMenuListener());
		
	}
	
	private void ReleaseDatabase() {
		File dir = null;
		File file = null;
		
		try
		{
			dir = new File("data/data/" + getPackageName() + "/databases");
			if (!dir.exists() || !dir.isDirectory())
			{
				dir.mkdir();
			}
			file = new File(dir, getString(R.string.database_file_name));
			if (!file.exists())
			{
				//if (android.os.Build.VERSION.SDK > 8 )
				InputStream is = null;
				if ( new Integer(android.os.Build.VERSION.SDK)  < 8)
				{
					is = getResources().openRawResource(R.raw.sdmanager2_1);
				}else {
					is = getResources().openRawResource(R.raw.sdmanager2_2);
				}
					
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buffer = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) > 0)
				{
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
		} catch (NotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void displayFileList(final String pathString) {
		final ProgressDialog pdDialog = ProgressDialog.show(MainActivity.this,getString(R.string.main_activity_processdialog_title),getString(R.string.main_activity_processdialog_text),
						true, true);
		
	        //设定Handler对象,主要是处理新开线程完毕后交给主线程来处理的数据 
	         mhandler = new Handler(){ 
	             @Override 
	             public void handleMessage(Message msg) 
	             { 
	        	     switch (msg.what) {
				case MESSGER_CLEAR_LIST_STRING:
					 clearListViewItem();
					break;
				case MESSGER_DISPLAY_LIST_STRING:
					SimpleAdapter simpleAdapter = (SimpleAdapter) msg.obj;
					
					listView.setAdapter(simpleAdapter);
					break;
				case MESSGER_SET_TITLE_STRING:
					
					setTitle(nowPathString);
					break;
				default:
					break;
			}
	        	                     
	             } 
	         }; 
		
		new Thread() {
			@Override
			public void run() {
				
				Message message = new Message();
				message.what = MESSGER_CLEAR_LIST_STRING;
				mhandler.sendMessage(message);

				nowPathString = pathString;
				message = new Message();
				message.what = MESSGER_SET_TITLE_STRING;
				mhandler.sendMessage(message);
				
				arrayList = new ArrayList<HashMap<String, Object>>();
				arrayList = new FileManagerService(MainActivity.this, pathString).getFileList();
				
				String sortByString = new SharePreferencesService(MainActivity.this).getSortBy();
				
				// 排序方式 文件名称
				if (sortByString.equals(getResources().getStringArray(R.array.set_activity_sort_by_Key)[1]))
				{
					new FileManagerService(MainActivity.this,pathString).sortByFileName(arrayList);
				}
				// 文件类型
				else if (sortByString.equals(getResources().getStringArray(R.array.set_activity_sort_by_Key)[2]))
				{
					new FileManagerService(MainActivity.this,pathString).sortByFileType(arrayList);
				}
				// 删除指数
				else if (sortByString.equals(getResources().getStringArray(R.array.set_activity_sort_by_Key)[3]))
				{
					new FileManagerService(MainActivity.this,pathString).sortByFileDelNo(arrayList);
				}
				//如果为跟目录则不添加返回上一次
				if (!nowPathString.equals(Environment.getExternalStorageDirectory().toString()))
				// 添加一条在最上面的返回记录
				{
					String parentString = new File(pathString).getParent();
//					Toast.makeText(getApplicationContext(), parentString, 1).show();
					
					HashMap<String, Object> hashMap = new HashMap<String, Object>();
					hashMap.put(getString(R.string.hashMapIcon),R.drawable.undo);
					hashMap.put(getString(R.string.hashMapName),getString(R.string.main_activity_list_undo_path));
					hashMap.put(getString(R.string.hashMapInfo),"..");
					hashMap.put(getString(R.string.hashMapPath),parentString);
					new String();
					hashMap.put(getString(R.string.hashMapIndex),String.valueOf(arrayList.size()));
					hashMap.put(getString(R.string.hashMapIsDir),new File(pathString).isDirectory() ? 0: 1);
					arrayList.add(0, hashMap);
				}
				
				SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this,arrayList,R.layout.main_list_item,
						new String[] {
								getString(R.string.hashMapIcon),
								getString(R.string.hashMapName),
								getString(R.string.hashMapInfo),
								getString(R.string.hashMapIndex) },
						new int[] {
								R.id.list_item_view_icon,
								R.id.list_item_view_title,
								R.id.list_item_view_text,
								R.id.list_item_view_del_no });
				
				
				 
				pdDialog.dismiss();
				message = new Message();
				message.what = MESSGER_DISPLAY_LIST_STRING;
				message.obj = simpleAdapter;
				mhandler.sendMessage(message);
			}
		}.start();
	}
	
	private void clearListViewItem() {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		arrayList=new ArrayList<HashMap<String,Object>>();
		arrayList.add(hashMap);
		SimpleAdapter simpleAdapter = new SimpleAdapter(this,
				arrayList, 
				R.layout.main_list_item, new String[] { getString(R.string.hashMapIcon), getString(R.string.hashMapName),getString(R.string.hashMapInfo),getString(R.string.hashMapIndex) },
				new int[] { R.id.list_item_view_icon,R.id.list_item_view_title,R.id.list_item_view_text,R.id.list_item_view_del_no });
		listView.setAdapter(simpleAdapter);
	}

	private void openFileWithSelectOpener(String pathString) {
	        Intent intent = new Intent();   
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
	        intent.setAction(android.content.Intent.ACTION_VIEW);   
	        String fileUriString = (String) nowSelectHashMap.get(getString(R.string.hashMapUri));
	        
		intent.setDataAndType(Uri.fromFile(new File(pathString)),fileUriString);   

		startActivity(intent);


//	       intent.setDataAndType(Uri.fromFile(new File(pathString)), "application/vnd.android.package-archive");   
//		startActivity(intent);   
	}

	private final class OnListViewCreateContextMenuListener implements View.OnCreateContextMenuListener
	{
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
			menu.setHeaderTitle(R.string.main_activity_edit_list_Title);
			
			menu.add(0, 0, 0, getString(R.string.main_activity_edit_list_open));
			menu.add(0, 1, 0, getString(R.string.main_activity_edit_list_view));
			menu.add(0, 2, 0, getString(R.string.main_activity_edit_list_edit));
			menu.add(0, 3, 0, getString(R.string.main_activity_edit_list_del));
		}
	}

	private final class OnListViewItemClickListener implements OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
			
			openFileOrDir(arg2);
			
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// 获得单击位置
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		nowSelectHashMap = new HashMap<String, Object>();
		nowSelectHashMap = arrayList.get(menuInfo.position);
		if (((String)nowSelectHashMap.get(getString(R.string.hashMapName))).equals("..")) 
			return  super.onContextItemSelected(item);
		
		
		// 如果为打开
		if (item.toString().equals(getString(R.string.main_activity_edit_list_open))) {
			openFileOrDir(menuInfo.position);
		}
		// 编辑
		else if (item.toString().equals(getString(R.string.main_activity_edit_list_edit)))
		{
			Intent intent = new Intent(this, EditActivityPre.class);
			intent.putExtra(getString(R.string.main_activity_2_edit_activity_Extra), nowSelectHashMap);
			startActivityForResult(intent, 22);
		}
		// 查看
		else if (item.toString().equals(getString(R.string.main_activity_edit_list_view)))
		{
			ViewAlertDialog viewAlertDialog = new ViewAlertDialog(MainActivity.this,nowSelectHashMap);
			viewAlertDialog.show();
			
		}
		// 删除
		else if (item.toString().equals(getString(R.string.main_activity_edit_list_del)))
		{
			Builder alertDialog =new AlertDialog.Builder(MainActivity.this);
			alertDialog.setTitle(getString(R.string.main_activity_delete_file_title));
			String message = String.format(getString(R.string.main_activity_delete_file_message_format),(String)nowSelectHashMap.get(getString(R.string.hashMapName)));
			alertDialog.setMessage(message);
			alertDialog.setIcon(android.R.drawable.ic_menu_info_details);
			alertDialog.setPositiveButton(getString(R.string.main_activity_delete_file_button_ok), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					FileManagerService fileManagerService = new FileManagerService(getApplicationContext(), (String)nowSelectHashMap.get(getString(R.string.hashMapPath)));
					if (fileManagerService.delete() == true)
					{
						Toast.makeText(getApplicationContext(), getString(R.string.main_activity_delete_file_success), 1).show();
						clearListViewItem();
						displayFileList(nowPathString);
					}else {
						Toast.makeText(getApplicationContext(), getString(R.string.main_activity_delete_file_failure), 1).show();
					}
					dialog.dismiss();
				}
			});
			alertDialog.setNegativeButton(getString(R.string.main_activity_delete_file_button_cancel), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					
				}
			});
			alertDialog.create().show();

		}
		
		return super.onContextItemSelected(item);
	}

	private void openFileOrDir(int nPos) {
		// 获得点击位置的数组信息
		nowSelectHashMap= arrayList.get(nPos);
		// 获得点击的路径信息
		String pathString =(String) nowSelectHashMap.get(getString(R.string.hashMapPath));
		// 判断是否为文件夹
		if (new File(pathString).isDirectory())
		{
			// 如果点击的信息为 内存卡 根目录，则停止
			if (pathString.equals(new File(Environment.getExternalStorageDirectory().toString()).getParent()))	return ;
			// 调用刷新文件列表信息
			displayFileList(pathString);
		}else
		{
			// 调用打开文件函数
			openFileWithSelectOpener(pathString);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,Intent data) {
		
		try
		{
			if (data.getStringExtra(getString(R.string.edit_activity_save_status_result_title)).equals(getString(R.string.edit_activity_save_status_result_success)))
			{
				displayFileList(new File ((String) nowSelectHashMap.get(getString(R.string.hashMapPath))).getParent());
			}
		} catch (Exception e)
		{
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK  )
		{
			if (nowPathString.equals(Environment.getExternalStorageDirectory().toString()))
			{
				return super.onKeyDown(keyCode, event);
			}else {
				openFileOrDir(0);
				return false;
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(getString(R.string.main_activity_menu_refresh)).setIcon(android.R.drawable.ic_menu_rotate);
		menu.add(getString(R.string.main_activity_menu_setting)).setIcon(android.R.drawable.ic_menu_preferences);
		menu.add(getString(R.string.main_activity_menu_exit)).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if (item.toString().equals(getString(R.string.main_activity_menu_exit)))
		{
			finish();
		}
		// 如果为i刷新
		else if (item.toString().equals(getString(R.string.main_activity_menu_refresh)))
		{
			clearListViewItem();
			displayFileList(nowPathString);
		}
		else if (item.toString().equals(getString(R.string.main_activity_menu_setting)))
		{
			Intent intent = new Intent(MainActivity.this, SetActivity.class);
			startActivity(intent);
		}
		
		return super.onOptionsItemSelected(item);
	}


	
	
	


	



}